package drongo.desktop.undo.shortKey
{
	import drongo.desktop.utils.KeyboardCodeUitls;

	/**
	 *快捷键数据单元 
	 * @author 蝈蝈
	 */	
	internal class ShortKeyData
	{
		public var focusTarget:String;
		/**
		 * 快捷键 
		 */		
		private var keyCodes:Array;
		/**
		 *快捷键描述 
		 */		
		public var label:String;
		/**
		 *
		 * 快捷键指令 
		 */		
		public var operate:String;
		/**
		 * 注册一个快捷键 
		 * @param operateKey									操作码
		 * @param keyCodes										按键列表
		 * @param focusTarget									焦点对象
		 * @param label												描述													
		 */
		public function ShortKeyData(operateKey:String,keyCodes:Array,focusTarget:String=null,label:String=null)
		{
			this.operate=operateKey;
			this.focusTarget=focusTarget;
			this.label=label;
			this.keyCodes=keyCodes.sort(Array.NUMERIC);
			_keyCode=keyCodes.join("+");
		}
		private var _keyCode:String;
		/**
		 * 经过排序的快捷键组合 
		 * @return 
		 */		
		public function get keyCode():String{
			return _keyCode;
		}
		public function get keyCodeString():String{
			var key:String="";
			var code:uint;
			if(keyCodes){
				for (var i:int = 0; i < keyCodes.length; i++) 
				{
					code=keyCodes[i];
					key+=KeyboardCodeUitls.keyCodeToKeyName(code);
					if(i<keyCodes.length-1){
						key+="+";
					}
				}
			}
			return key;
		}
		/**
		 * 获取快捷键组合 
		 * @param keyCodes
		 * @return 
		 */		
		public static function getKey(keyCodes:Array):String{
			var codes:Array=keyCodes.sort(Array.NUMERIC);
			return keyCodes.join("+");
		}
		/**
		 * 通过参数获取完全操作KEY
		 * @param operate
		 * @param keyCodes
		 * @param focusTarget
		 * @return 
		 */		
		public static function getOperateKey(operate:String,keyCodes:Array,focusTarget:String=null):String{
			var key:String=getKey(keyCodes);
			return operate+"+"+key+"+"+focusTarget;
		}
		//============================================数据编解码=================================//
		public static function Decode(value:ShortKeyData):XML{
			var xml:XML=<shortcut></shortcut>;
			xml.@focusTarget=value.focusTarget;
			xml.@keyCode=value.keyCodeString;
			xml.@operate=value.operate;
			if(value.label){
				xml.@label=value.label==null?"":value.label;
			}
			return xml;
		}
		public static function Encode(xml:XML,value:ShortKeyData):ShortKeyData{
			var focusTarget:String=xml.@focusTarget;
			var keyCode:String=xml.@keyCodeString;
			var keyCodes:Array=keyCode.split("+");
			for (var i:int = 0; i < keyCodes.length; i++) 
			{
				keyCodes[i]=KeyboardCodeUitls.keyCharToKeyCode(keyCodes[i]);
			}
			var operate:String=xml.@operate;
			var label:String=xml.@label;
			
			value||=new ShortKeyData(operate,keyCodes,focusTarget,label);
			return value;
		}
	}
}